package model.audio;

public class SoundProcessor {

	private float sampleRate;
	private float micVolumePercent;
	private Filter filter=null;
	
	public static final float DEFAULT_MIC_VOLUME=1f;
	
	public SoundProcessor(float sampleRate){
		this.sampleRate=sampleRate;
		filter=new Filter();
		micVolumePercent=DEFAULT_MIC_VOLUME;
	}
	
	public byte[] process(byte out[]){
		Complex ifft_out[]=byteToComplex(out); //转到频域
		Complex fft_out[]=FFT.fft(ifft_out);
		
		fft_out=filter(fft_out);        //过滤
	    
		ifft_out=FFT.ifft(fft_out);    //转回时域
		out=complexToByte(ifft_out);
		
	    out=adjustVolume(out);    
	    return out;
	}
	
	public void setMicroVolume(float value){
		if(value>1){
			value=1;
		}else if(value<0){
			value=0;
		}
		micVolumePercent=value;
	}
	
	private byte[] adjustVolume(byte data[]){  		//麦克风音量
		for(int i=0;i<data.length;i++){			
			data[i]=(byte) (data[i]*micVolumePercent);		
		}
		return data;
	}
	
	private Complex[] filter(Complex fft_out[]){
		fft_out=filter.frequency_filter(sampleRate,fft_out, 0, 85);       
		fft_out=filter.frequency_filter(sampleRate,fft_out, 1400,2048);   //过滤声音
		return fft_out;
	}
	
	private Complex[] byteToComplex(byte[] data){
		int N=data.length;             //fft点数  
		Complex[] x=new Complex[N];    
		for(int i=0;i<N;i++){
			x[i]=new Complex(data[i],0);
		}
		return x;
	}
	
	private byte[] complexToByte(Complex data[]){
		int N=data.length; 
		byte result[]=new byte[N];
		for(int i=0;i<N;i++){
			result[i]=(byte) data[i].re();                //
		}
		return result;
	}
	
}
